package tpaagp.scheduleus;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

public class SpecifyAvailability extends Activity{
	
	final int MONDAY = 0;
	final int TUESDAY = 1;
	final int WEDNESDAY = 2;
	final int THURSDAY = 3;
	final int FRIDAY = 4;
	final int SATURDAY = 5;
	final int SUNDAY = 6;
	final int DAYS_PER_WEEK = 7;
	final int HOURS_PER_DAY = 24;
	
	private String dow[] = {"mon", "tue", "wed", "thu", "fri", "sat", "sun"};
	private String daysOfTheWeek[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
	private String hours[] = {
			"0:00",
	        "1:00",
	        "2:00",
	        "3:00",
	        "4:00",
	        "5:00",
	        "6:00",
	        "7:00",
	        "8:00",
	        "9:00",
	        "10:00",
	        "11:00",
	        "12:00",
	        "13:00",
	        "14:00",
	        "15:00",
	        "16:00",
	        "17:00",
	        "18:00",
	        "19:00",
	        "20:00",
	        "21:00",
	        "22:00",
	        "23:00"
			
	};
	
	private CheckBox checked[] = new CheckBox[HOURS_PER_DAY];
	private int currentDay = MONDAY;
	
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.specify);
		
		LinearLayout ll = (LinearLayout) findViewById(R.id.list_hours);
		for (int i = 0; i < HOURS_PER_DAY; i++) {
			CheckBox cb = new CheckBox(this);
			cb.setText(hours[i]);
			checked[i] = cb;
			ll.addView(cb);
		}
		fillListView();
		
		//Set the buttons
		Button next = (Button) findViewById(R.id.next_button);
		Button prev = (Button) findViewById(R.id.button_previous);
		prev.setEnabled(false);
		
		next.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				saveState(false);
				changeDay("next");
			}
		});
		
		
		prev.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				saveState(false);
				changeDay("prev");
			}
		});
	}
	
	private void fillListView() {
		
		//Set the textview
		TextView t = (TextView) findViewById(R.id.day);
		t.setText(daysOfTheWeek[currentDay]);
		
		//Get availability stored in the phone
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		String avOnDay = prefs.getString(dow[currentDay], "000000000000000000000000");
		
		for (int i = 0; i < HOURS_PER_DAY; i++) {
			boolean enabled = (avOnDay.charAt(i) == '1');
			checked[i].setChecked(enabled);
		}
	}
	
	
	private void saveState(boolean finish) {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		SharedPreferences.Editor ed = prefs.edit();
		String abailability = "";
		//Check the state of the checkboxes, and construct the string to save
		for(int i = 0; i < HOURS_PER_DAY; i++) {
			if (checked[i].isChecked()) abailability += '1';
			else abailability += '0';
		}
		ed.putString(dow[currentDay], abailability);
		if(!ed.commit()){
			System.out.println("MEEC");
		}
		if (finish) {
			ed.putBoolean("availability",true);
			ed.commit();
			sendInfoToServer();
			finish();
		}
	}
	
	
	private void changeDay(String buttonPressed) {
		if (buttonPressed == "next") currentDay++;
		else currentDay--;
		Button next = (Button) findViewById(R.id.next_button);
		Button prev = (Button) findViewById(R.id.button_previous);
		TextView tv = (TextView) findViewById(R.id.day);
		tv.setText(daysOfTheWeek[currentDay]);
		
		if (currentDay == SUNDAY) {
			//Change the next button to save and change also the onclicklistener
			next.setText("Save");
			next.setOnClickListener(new Button.OnClickListener() {
				public void onClick(View v) {
					saveState(true);
				}
			});
		}
		else if (currentDay == MONDAY) {
			prev.setEnabled(false);
		}
		else {
			prev.setEnabled(true);
		}
		fillListView();
	}
	
	private void sendInfoToServer() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		String user = prefs.getString("Name", "user");
		String urlS = prefs.getString("URL", "url");

		//Build the get query
		String availability = "";
		for (int i = 0; i < DAYS_PER_WEEK; i++) {
			boolean first = true;
			String av_day = prefs.getString(dow[i], "000000000000000000000000");
			availability = availability + dow[i] + "=";
			for (int j = 0; j < HOURS_PER_DAY; j++) {
				if (av_day.charAt(j) == '1') {
					if (!first) availability += '-';
					else first = false;
					availability += j;
				}
			}
			if (i < DAYS_PER_WEEK -1) availability += '&';
		}
		
		String queryString = "enviar_disponibilidad.php?user="+user+"&"+availability;
		
		HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(urlS+queryString);
		try {
			client.execute(request);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
